clear
do "...\First.do"

********************************************************************************
* Find clinics closures based on last date of services
********************************************************************************

clear
use "$raw\gp_services_all.dta"
drop if pnr==""

keep ydernr honuge

g year=substr(honuge,1,2)
g week=substr(honuge,3,2)

destring year, replace
destring week, replace

replace year=1900+year if year>50
replace year=2000+year if year<50

g date=yw(year, week)
format date %tw

bys ydernr: egen first=min(date)
bys ydernr: egen last=max(date)
format first %tw
format last %tw

keep ydernr first last 
duplicates drop

rename first first_gp
rename last last_gp

save "$work\gp_closures.dta", replace

********************************************************************************
********************************************************************************

clear
use "$work\gp_closures.dta"

* min year
g help=first_gp
format help %10.0g
g help_date=dofw(help)
format help_date %td

g year_min=year(help_date)

drop help help_date

* max year
g help=last_gp
format help %10.0g
g help_date=dofw(help)
format help_date %td

g year_max=year(help_date)

drop help help_date
drop first_gp last_gp
duplicates drop

tab year_min
tab year_max

save "$work\gp_closures_year.dta", replace

g year=year_min

fillin ydernr year
drop _fillin

sort ydernr year_min
replace year_min=year_min[_n-1] if ydernr==ydernr[_n-1] & missing(year_min)
replace year_max=year_max[_n-1] if ydernr==ydernr[_n-1] & missing(year_max)

sort ydernr year

drop if year<year_min
drop if year>year_max

tab year


save "$work\gp_closures_yearly.dta", replace





********************************************************************************
* Drop closures, where the doctors just get a new doctor id
********************************************************************************

clear 
use "$work\Yder_9518_long.dta"

merge m:1 ydernr using "$work\gp_closures_year.dta"
drop if _merge==1
replace year_max=. if year_max>2017
order ydernr pnr year_max

sort pnr year

* Each doctors's first and last year in a GP clinic
bys pnr: egen min_year_pnr=min(year)
bys pnr: egen max_year_pnr=max(year)

order ydernr pnr year_max min_year_pnr max_year_pnr

g merger_help=(year_max<max_year_pnr)
bys ydernr: egen merger=max(merger_help)
replace year_max=. if merger==1

keep ydernr year_max
duplicates drop


save "$work\gp_closures_year.dta", replace






